/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;

import scheduler.databean.Course;
import scheduler.databean.Schedule;
import scheduler.databean.Section;
import scheduler.databean.User;
import scheduler.formbean.AddForm;
import scheduler.formbean.LoginForm;

import scheduler.model.CourseDao;
import scheduler.model.Model;
import scheduler.model.ScheduleDao;
import scheduler.model.SectionDao;

public class ScheduleAction extends Action {
	private static FormBeanFactory<AddForm> formBeanFactory =
		FormBeanFactory.getInstance(AddForm.class,"<>\"");

	//private BookmarkDao entryDAO;

	private ScheduleDao scheduleDao;
	private CourseDao courseDao;
	private SectionDao sectionDao;
	private Model model;

	public ScheduleAction(Model model) {
		scheduleDao= model.getScheduleDao();
		courseDao= model.getCourseDao();
		sectionDao = model.getSectionDao();
		this.model=model;
	}

	public String getName() { return "schedule.do"; }
	
	public String parseSectionId(String sectionId) {
		return sectionId.substring(0, 2) + "-" + sectionId.substring(2, 5) + " " + sectionId.substring(5);
	}
	
	public String perform(HttpServletRequest request) {
		try {
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute("user");
			if (user == null) {
				LoginForm form = new LoginForm();
				form.setRedirect("/add-bookmark.do");
				request.setAttribute("form",form);
				return "login.jsp";
			}

			String which=request.getParameter("which");			
			if (which==null) {//see if radio button pressed
				which=(String) request.getSession().getAttribute("which");
				if (which==null) {					
					which="";
				}
			} else {
				if(request.getSession().getAttribute("which")!=null
						&& request.getSession().getAttribute("which").equals(which))
				{
					which="";
					request.getSession().setAttribute("which", null);
				}
				request.getSession().setAttribute("which", which);
			}

			int scheduleID;			

			String ID=request.getParameter("scheduleID");
			if(ID!=null &&ID.length()!=0){
				scheduleID= Integer.parseInt(ID);
				request.getSession().setAttribute("scheduleID", scheduleID);
			}else
			{	             
				scheduleID=Integer.parseInt(request.getSession().getAttribute("scheduleID").toString());
			}

			if(request.getParameter("current")!=null)
			{
				user.setCurrentSchedule(scheduleID);
			}

			ScheduleTable st= new ScheduleTable(model);

			// Must be logged in for this one
			List<String> errors = new ArrayList<String>();
			AddForm form = formBeanFactory.create(request);
			request.setAttribute("form",form);

			if(form.submitted()){
				if(courseDao.lookup(form.getCourseNumber())!=null){
					if(sectionDao.lookup(Integer.toString(form.getCourseNumber())+form.getSection())!=null)
					{
						Schedule added[] =scheduleDao.CheckAdded(user.getUserName(), scheduleID, form.getCourseNumber());
						if(added.length==0){
							scheduleDao.create(user.getUserName(), scheduleID, form.getCourseNumber(), form.getSection(), sectionDao.lookup(Integer.toString(form.getCourseNumber())+form.getSection()).getYear(), sectionDao.lookup(Integer.toString(form.getCourseNumber())+form.getSection()).getSemester());
						}
						else{
							errors.add("Course already Added");
						}
					}
					else{
						errors.add("Section does not exists");
					}
				}
				else{
					errors.add("Course does not exists");
				}
			}

			Schedule[] list = scheduleDao.getSchedule(user.getUserName(), scheduleID);

			String choices = "<ul id=\"courseList\">\n";
			for (int i = 0; i < list.length; i++) {
				int tempCourseId = list[i].getCourseId();
				Course tempCourse = courseDao.lookup(tempCourseId);
				choices += "<li style=\"background: #" + (167 * tempCourseId) + "\">\n" +
							"<div class=\"course\">" +
							"<form name=\"delete\" action=\"delete.do\" method=\"post\">\n" +
							"<a class=\"courseNumber\" href=\"schedule.do?which=" + tempCourseId + "\" title=\"Click to switch sections for this course\">" + parseSectionId(list[i].getSectionId()) + "</a>\n" +				
							"<input type=\"hidden\" name=\"idString\" value=\"" + list[i].getId() + "\"/>\n" +
							
							"<form name=\"groovyform\"><input type=\"submit\" name=\"groovybtn1\" class=\"groovybutton\" value=\"X\"/ title=\"Click to drop this course\" onMouseOver=\"goLite(this.form.name,this.name)\" onMouseOut=\"goDim(this.form.name,this.name)\">\n" +
							"<a class=\"description\" target=\"_blank\" href=\"course.do?course=" + list[i].getCourseId() + "\" title=\"Click to view a description for this course\">Description</a>\n"+
							"<h4 class=\"courseName\">" + tempCourse.getCourseName() +"   " + tempCourse.getUnit() + " units </h4> </form>\n" +
						//	"<div class=\"units\">" + tempCourse.getUnit() + " units</div>\n" +
														
							"</form>\n" ;
							

				if (which.equals(Integer.toString(list[i].getCourseId()))) {
					choices += "<form name=\"change\" action=\"edit.do\" method=\"post\">\n" ;
					Section[] sec = sectionDao.getSectionForCourse(list[i].getCourseId());
					for(int j = 0; j < sec.length; j++)	{

						choices += "<input type=\"radio\" name=\"section\"" ;
						if(sec[j].getId().equals(list[i].getSectionId())){
							choices+="CHECKED";
						}
						choices+=	" value=\"" + sec[j].getSectionName() + "\" onClick=\"this.form.submit()\">" + sec[j].getSectionName() +
						"<input type=\"hidden\" name=\"id\" value=\"" + list[i].getId() + "\"/>\n" ; 
					}
					choices+="</form>\n";
				}
				choices+="</div>" +
				"</li>";
			}

			if (user.getCurrentSchedule() != scheduleID) {
				choices += "<form action=\"schedule.do?current=true\" method=\"post\">\n"+
				"<input type=\"submit\" name=\"button\" value=\"Set Current\"/>\n"+
				"</form>\n";
			}

			String page=st.drawSchedule(user, scheduleID);

			if (page == null)
				request.setAttribute("page", "Schedule Load error");
			else
				request.setAttribute("page", page);
			
			request.setAttribute("choices", choices);
			request.setAttribute("errors", errors);

			// Any validation errors?
			errors.addAll(form.getValidationErrors());
			if (errors.size() != 0)
				request.setAttribute("errors",errors);

			request.getSession().setAttribute("user", user);
			
			return "temp.jsp";
		} catch (DAOException e) {
			e.printStackTrace();
			request.setAttribute("dbError",e.getMessage());
			return "db-error.jsp";
		}
	}
}
